package service

import (
	"github.com/ahmetb/go-linq/v3"
	"gorm.io/gorm"
	"hcy-api/structs/lms"
	"hcy-api/structs/tables"
	"lms/global"
	"lms/repository"
	"strings"
)

var CourseService = new(courseService)

type courseService struct {
}

// DeleteCourse 删除课程，同步删除课程的映射关系
func (s courseService) DeleteCourse(id int64) (err error) {
	err = global.DB.Transaction(func(tx *gorm.DB) error {
		// 1.删除课程
		if err = tx.Where(&tables.Course{Id: id}).Delete(&tables.Course{}).Error; err != nil {
			return err
		}
		// 2.删除课程和部门的映射
		if err = tx.Where(&tables.MapCourse2Org{CourseId: id}).Delete(&tables.MapCourse2Org{}).Error; err != nil {
			return err
		}
		// 3.删除课程和用户的映射
		if err = tx.Where(&tables.MapCourse2User{CourseId: id}).Delete(&tables.MapCourse2User{}).Error; err != nil {
			return err
		}
		return nil
	})
	return
}

// PublishCourse 发布课程
func (s courseService) PublishCourse(in lms.PublishCourseDto) (err error) {
	err = global.DB.Transaction(func(tx *gorm.DB) error {
		var cour = new(tables.Course)
		err = tx.Where(&tables.Course{Id: in.CourseId}).Find(cour).Error
		if in.IsPublic {
			cour.IsPublic = true
			err = tx.Save(cour).Error
			if err != nil {
				return err
			}
		}
		if len(in.OrgIds) > 0 {
			// 写入部门映射
			li := make([]tables.MapCourse2Org, 0)
			for _, v := range in.OrgIds {
				li = append(li, tables.MapCourse2Org{
					CourseId: cour.Id,
					OrgId:    v,
				})
			}
			err = tx.CreateInBatches(&li, len(li)).Error
			if err != nil {
				return err
			}
		}
		if len(in.UserIds) > 0 {
			// 写入用户映射
			li := make([]tables.MapCourse2User, 0)
			for _, v := range in.UserIds {
				li = append(li, tables.MapCourse2User{
					CourseId: cour.Id,
					UserId:   v,
				})
			}
			err = tx.CreateInBatches(&li, len(li)).Error
			if err != nil {
				return err
			}
		}
		return nil
	})
	return err
}

// GetCourse 获取课程
func (s courseService) GetCourse(in lms.SearchCourse, uid int64, orgId int64) (li []tables.Course, err error) {
	var (
		publicLi []tables.Course
		orgLi    []tables.Course
		userLi   []tables.Course
		all      []tables.Course
	)
	// 1.获取公开的课程
	if publicLi, err = repository.CourseDB.FindPublicCourse(); err != nil {
		return
	}
	// 2.获取部门课程
	if orgLi, err = repository.CourseDB.FindOrgCourse([]int64{orgId}); err != nil {
		return
	}
	// 3.获取个人课程
	if userLi, err = repository.CourseDB.FindUserCourse([]int64{uid}); err != nil {
		return
	}
	// 4.去重
	all = append(all, publicLi...)
	all = append(all, orgLi...)
	all = append(all, userLi...)
	query := linq.From(all).DistinctBy(func(item interface{}) interface{} {
		return item.(tables.Course).Id
	})
	if in.Name != "" {
		query.Where(func(item interface{}) bool {
			t := item.(tables.Course)
			return strings.Contains(t.Name, in.Name)
		})
	}
	if in.FolderId != 0 {
		query.Where(func(item interface{}) bool {
			t := item.(tables.Course)
			return t.FolderId == in.FolderId
		})
	}
	query.ToSlice(&li)
	return
}

// CheckCourseJurisdiction 检查课程权限
func (s courseService) CheckCourseJurisdiction(courseId int64, userId int64, orgId int64) (b bool, err error) {
	var (
		cou *tables.Course
	)
	if cou, err = repository.CourseDB.FindById(courseId); err != nil {
		return false, err
	}
	if cou.IsPublic {
		return true, err
	}
	b, err = repository.CourseDB.CheckCourseMapOrg(orgId, courseId)
	if err != nil {
		return false, err
	}
	if b {
		return true, err
	}
	b, err = repository.CourseDB.CheckCourseMapUser(userId, courseId)
	return
}
